package com.sky.controller.user;

import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/user/dish")
@RestController("userDishController")
@Slf4j
@Api(tags = "菜品相关接口")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品及其关联口味
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishVO>> list(Long categoryId) {

        //构造redis中的key，规则：dish_categoryId
        String key = "dish_" + categoryId;

        //查询redis是否存在对应菜品数据
        List<DishVO> listDishVO = (List<DishVO>) redisTemplate.opsForValue().get(key);

        //如果存在缓存，则直接返回
        if(listDishVO != null && listDishVO.size() != 0) {
            return Result.success(listDishVO);
        }

        log.info("根据种类id：{}查询菜品", categoryId);
        List<DishVO> list = dishService.selectWithFlavorByCategoryId(categoryId);

        //如果不存在缓存，则写入redis
        redisTemplate.opsForValue().set(key, list);

        return Result.success(list);
    }

}
